import axios from 'axios'
import { ElMessage } from 'element-plus'
import auth from '@/store/auth'
import router from '@/router'

const request = axios.create({
  baseURL: '/api',
  timeout: 5000,
  withCredentials: true
})

request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => response,
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          auth.clearUser()
          const currentPath = router.currentRoute.value.fullPath
          if (currentPath !== '/login') {
            router.push({
              path: '/login',
              query: { redirect: currentPath }
            })
          }
          ElMessage.error('请先登录')
          break
        case 403:
          ElMessage.error('没有权限执行此操作')
          break
        default:
          ElMessage.error(error.response.data?.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
    return Promise.reject(error)
  }
)

export default request 